#!/usr/bin/env python3
"""Docstring for the token_email_generator.py module.

@author Juntong
@date   2022-10-17

用于生成Toke和邮件
"""

import os
import re
import random

import yaml

PROJECT_PATH = os.path.dirname(__file__)


def get_name_list(path=os.path.join(PROJECT_PATH, "SData", "name_list.csv"), key=",") -> list[tuple[str, str]]:
    with open(path, "r", encoding="utf-8") as fp:
        text = fp.read()

    lines = text.splitlines()
    items = [i.split(key) for i in lines]
    return [(a.strip(), b.strip()) for a, b in items]


def generate_token():
    """
    生成密钥
    """
    pws = []
    letter_num = 6 - random.randint(2, 4)
    letter_large_num = random.randint(1, letter_num - 1)
    letter_lower_num = letter_num - letter_large_num
    number_num = 6 - letter_num

    for i in range(number_num):
        pws.append(str(random.randint(0, 9)))
    for i in range(letter_large_num):
        pws.append(chr(random.randint(65, 90)))
    for i in range(letter_lower_num):
        pws.append(chr(random.randint(97, 122)))

    random.shuffle(pws)
    return "".join(pws)


def write_token_to_file(usernames, path=os.path.join(PROJECT_PATH, "SData/passwords.yaml")):
    with open(path, "r", encoding="utf-8") as fp:
        data = yaml.safe_load(fp)

    if not isinstance(data, dict):
        data = {}

    for username in usernames:
        m = re.match(r"(\w+)\.(\w+?)(\d+)", username)
        if m:
            a, b, c = m.groups()
            username = f"{a.capitalize()}.{b.capitalize()}{c}"
        data[username] = generate_token()

    with open(path, "w", encoding="utf-8") as fp:
        yaml.safe_dump(data, fp)

    return data


EMAIL_TEXT = """{name}你好：
感谢你报名选修课 Python 实用入门, 本节课进行签到, 你的登录Token为：

{token}

谢谢！


此致敬礼！
选修课Python实用开发入门讲师，21 TE 朱俊同

"""


def get_email_text(path=os.path.join(PROJECT_PATH, "SData/passwords.yaml")):

    name_list = get_name_list()
    email_name_dict = {b: a for a, b in name_list}

    email_token = get_name_list(path, ":")

    print(email_name_dict)

    for email, token in email_token:
        name = email_name_dict.get(email, "同学")
        text = EMAIL_TEXT.format_map({"name": name, "token": token})
        yield email + "@student.xjtlu.edu.cn", text

